<?php
/********************************
*   Common function for MySQL   *
********************************/

function connect_database( $dbhost, $dbName, $uname, $pass )
{
    $conn = mysql_connect("$dbhost", "$uname", "$pass") or die("System busy, please try to connect again later!");
	mysql_select_db($dbName, $conn) or die("System too busy, please try USE DB again later!" . mysql_error());

	return $conn;
}   

function check_mysql_error( $comm )
{
    $error = mysql_error( );

    if($error !="")
    {
        echo "comm:$comm<br> error:$error<br>Server databse operation error!";
        return false;
	}
    return true;
}

function exec_sql( $conn, $comm )
{
    mysql_query($comm, $conn);
    if(check_mysql_error($comm))
    {
        return true;
    }
    return false;
}


function get_query_list( $conn, $sql )
{
    $result = mysql_query($sql) or check_mysql_error($sql);
    $num_fields = mysql_num_fields($result);
    

    $i = 0;
    $j = 0;
	while( $row = mysql_fetch_array($result) )
	{
        for($j=0; $j<$num_fields; $j++)
        {
            $name = mysql_field_name($result, $j);
            $object[$i][$name] = $row[$name];
        }
        $i++;
    }
    mysql_free_result($result);

    return $object;
}


function gotoLocation($location)
{
	echo '<script language="javascript1.2">';
	echo  "window.location.replace('".$location."');";
	echo "</script>";
}

function sqlPart($value, $defaultValue, $fieldType, $comma)
{
	$sqlpart = "";
	$isStr = ($fieldType == "string");
	if($isStr)
	{
		$sqlpart .= "'";
	}
	if(empty($value)){
		$sqlpart .= $defaultValue;
	}else{
	   $sqlpart .= $value;
	}
	if($isStr)
		$sqlpart .= "'";
	if($comma)
		$sqlpart .= ", ";
	return $sqlpart;
}


function get_query_row( $conn, $sql )
{
    $result = mysql_query($sql) or check_mysql_error($sql);
    $num_fields = mysql_num_fields($result);

    $j = 0;
	if( $row = mysql_fetch_array($result) )
	{
        for($j=0; $j<$num_fields; $j++)
        {
            $name = mysql_field_name($result, $j);
            $object[$name] = $row[$name];
        }
    }
    mysql_free_result($result);

    return $object;
}


function get_a_value( $conn, $sql )
{
    $result = mysql_query($sql) or check_mysql_error($sql);
    $num_fields = mysql_num_fields($result);

    $row = mysql_fetch_array($result);

    return $row[0];
}

function read_table($conn, $sql)
{
	$result = mysql_query($sql) or die("Query failed");

	print "<table>\n";
	    while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
	        print "\t<tr>\n";
	        foreach ($line as $col_value) {
	            print "\t\t<td>$col_value</td>\n";
	        }
	        print "\t</tr>\n";
	    }
	    print "</table>\n";

	    /* Free resultset */
	mysql_free_result($result);
}
?>